/* eslint-disable react/no-string-refs */

import React, { Component } from 'react';
import styled from 'styled-components/native';
import _ from 'lodash';
import { ActivityIndicator, Keyboard, AsyncStorage } from 'react-native';
import { graphql, compose } from 'react-apollo';
import { connect } from 'react-redux';

import {
  TextInputCom, RoundCornerButton,
  LinkText, ToolbarButton
} from '../components/common';

import { TOKEN } from '../types';
import { login } from '../actions/user';
import { colors } from '../utils/constants';
import { goBack, toTweetsListView } from '../actions/nav';
import SIGN_UP_MUTATION from '../graphql/mutations/signup';

const Root = styled.View`
  flex: 1;
  backgroundColor: ${ colors.WHITE };
`;

const LoadingView = Root.extend `
  alignItems: center;
  justifyContent: center;
`;

const TitleContent = styled.View`
  width: 100%;
  height: 81;
  alignItems: center;
  justifyContent: center;
`;

const Title = styled.Text`
  fontSize: 22;
  color: ${ colors.PRIMARY_TEXT };
`;

const TextInput = styled(TextInputCom)`
  marginLeft: 10;
`;

const RegisterButton = styled(RoundCornerButton)`
  marginLeft: 10;
  marginRight: 10;
  marginTop: 30;
`;

const RegisterInfosContent = styled.Text`
  fontSize: 15;
  color: ${colors.PRIMARY_TEXT_LITE};
  marginLeft: 10;
  marginRight: 10;
  marginTop: 8;
`;

const RegisterInfoLink = styled(LinkText)`
  fontSize: 15;
`;

class RegisterScreen extends Component {

  static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;
    let headerLeft = (
      <ToolbarButton text="取消" onPressed={params.goBack ? params.goBack : () => null} />
    );
    if (params.isProcessing) {
      headerLeft = null;
    }
    return { headerLeft };
  }

  state = {
    email: '',
    fullname: '',
    nickname: '',
    password: '',
    errors: {},
    isProcessing: false
  }

  componentDidMount() {
    this.props.navigation.setParams({
      goBack: this._goBack,
      isProcessing: this.state.isProcessing
    });
  }

  _goBack = () => {
    Keyboard.dismiss();
    this.props.goBack();
  }

  _onTextChanged = (type, value) => {
    const newState = _.clone(this.state);
    if (this.state.errors[type]) {
      delete newState.errors[type];
    }
    newState[type] = value;
    this.setState(newState);
  }

  _isReadyToSubmit = () => {
    const { email, fullname, nickname, password } = this.state;
    if (email && fullname && nickname && password && _.isEmpty(this.state.errors)) {
      return true;
    }
    return false;
  }

  _updateActionbar = params => {
    this.props.navigation.setParams(params);
  }

  _submit = async () => {
    Keyboard.dismiss();
    this.setState({ isProcessing: true });
    this._updateActionbar({ isProcessing: true });

    // 向服务器提交注册的数据
    const { email, fullname, nickname, password } = this.state;
    try {
      const { data } = await this.props.mutate({
        variables: {
          email,
          fullname,
          username: nickname,
          password
        }
      });
      await AsyncStorage.setItem(TOKEN, data.signup.token);
      this.setState({ isProcessing: false });
      this._updateActionbar({ isProcessing: false });
      this.props.login();
      this.props.toTweetsListView();
    } catch (error) {
      this.setState({
        isProcessing: false,
        errors: { global: error.graphQLErrors[0].message }
      });
      this._updateActionbar({ isProcessing: false });
    }
  }

  render() {
    if (this.state.isProcessing) {
      return (
        <LoadingView>
          <ActivityIndicator size="large" />
        </LoadingView>
      );
    }
    return (
      <Root>
        <TitleContent>
          <Title>输入邮箱，快速注册</Title>
        </TitleContent>
        <TextInput
          innerRef={r => { this.email = r }}
          autoFocus={!this.state.email}
          placeholder="请输入邮箱"
          returnKeyType="next"
          autoCapitalize="none"
          autoCorrect={false}
          blurOnSubmit={false}
          keyboardType="email-address"
          onChangeText={value => this._onTextChanged("email", value)}
          onSubmitEditing={() => this.fullname.TextInput.focus()}
          value={this.state.email || ''}
          error={!!this.state.errors.email}
          errorMsg={this.state.errors.email || ''}
        />
        <TextInput
          innerRef={r => { this.fullname = r }}
          placeholder="请输入您的真实姓名"
          returnKeyType="next"
          autoCapitalize="words"
          autoCorrect
          blurOnSubmit={false}
          onChangeText={value => this._onTextChanged("fullname", value)}
          onSubmitEditing={() => this.nickname.TextInput.focus()}
          value={this.state.fullname || ''}
          error={!!this.state.errors.fullname}
          errorMsg={this.state.errors.fullname || ''}
        />
        <TextInput
          innerRef={r => { this.nickname = r }}
          placeholder="请输入您的昵称"
          returnKeyType="next"
          autoCapitalize="words"
          autoCorrect={false}
          blurOnSubmit={false}
          onChangeText={value => this._onTextChanged("nickname", value)}
          onSubmitEditing={() => this.password.TextInput.focus()}
          value={this.state.nickname || ''}
          error={!!this.state.errors.nickname}
          errorMsg={this.state.errors.nickname || ''}
        />
        <TextInput
          innerRef={r => { this.password = r }}
          placeholder="请输入一个新密码，8~16位"
          returnKeyType="go"
          autoCapitalize="none"
          autoCorrect={false}
          secureTextEntry
          maxLength={16}
          onChangeText={value => this._onTextChanged("password", value)}
          onSubmitEditing={() => {
            if (this._isReadyToSubmit()) {
              this._submit();
            }
          }}
          value={this.state.password || ''}
          error={!!this.state.errors.password}
          errorMsg={this.state.errors.password || ''}
        />
        <RegisterButton
          disabled={!this._isReadyToSubmit()}
          onPress={() => this._submit()}
          text="注册"
        />
        <RegisterInfosContent>
          注册表示你同意
          <RegisterInfoLink url="https://www.google.com"> 微博个人信息保护政策 </RegisterInfoLink>
          和
          <RegisterInfoLink url="https://www.baidu.com"> 微博服务使用协议 </RegisterInfoLink>
        </RegisterInfosContent>
      </Root>
    );
  }
}

export default compose(
  graphql(SIGN_UP_MUTATION),
  connect(null, { goBack, login, toTweetsListView })
)(RegisterScreen);
